#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "myconfig.h"

static MyConfig _default_config;

int myconfig_init(const char *filename)
{
	FILE *fp;
	char buf[1024];
	MyConfig *tmpmc;
	char *p,*q;
	int c;

	if (!filename) return -1;

	memset((void *)&_default_config, 0 , sizeof(MyConfig));
	tmpmc=&_default_config;

	if ((fp=fopen(filename,"r")) == NULL)
	{
		return -1;
	}

	while(fgets(buf,sizeof(buf),fp))
	{
		p = (char *)strchr(buf,'\n');
		if (!p)
		{
			while ((c = getc (fp)) >= 0 && c != '\n')
				;
		}
		else
		{
			*p = 0;
		}
		if ((p = (char *) strchr (buf, '#')) != 0)
			*p = 0;

		for (p = buf; *p; p++)
			if (!isspace ((int) (unsigned char) *p))
				break;
		if (*p == 0)
			continue;

		for (; *p; p++)
			if (isspace ((int) (unsigned char) *p) || *p == '=')
				break;
		if (*p == 0)
			continue;
		*p++ = 0;

		while (*p && isspace ((int) (unsigned char) *p))
			++p;
		if (*p == '"')
		{
			++p;
			q = (char *) strchr (p, '"');
			if (q)
				*q = 0;
		}
		myconfig_set(buf,p);
	}
	fclose(fp);
	return 0;
}

const char *myconfig_get(const char *name)
{
	MyConfig *p;

	if (!name) return NULL;

	p=&_default_config;
	while(p)
	{
		if (p->name && !strcasecmp(p->name,name))
		{
			return p->value;
		}
		p=p->next;
	}
	return NULL;
}

const char *myconfig_set(const char *name, const char *value)
{
	MyConfig *p,*q;

	if (!name || !value) return NULL;

	p=&_default_config;
	q=p;
	while(p)
	{
		if (p->name && !strcasecmp(p->name,name))
		{
			if (p->value) free(p->value);
			p->value=strdup(value);
			return p->value;
		}
		q=p;
		p=p->next;
	}
	p=(MyConfig *)malloc(sizeof(MyConfig));
	p->name=strdup(name);
	p->value=strdup(value);
	p->next=NULL;
	q->next=p;
	return p->value;
}

void myconfig_destroy()
{
	MyConfig *p,*q;

	p=(&_default_config)->next;
	while(p)
	{
		if (p->name) free(p->name);
		if (p->value) free(p->value);
		q=p;
		p=p->next;
		free(q);
	}
	return;
}


